#!/usr/bin/env python3
import psutil
import socket
import requests
from datetime import datetime

cpu_url = "http://192.168.88.1:8000/v1/cpu"
mem_url = "http://192.168.88.1:8000/v1/mem"
disk_url = "http://192.168.88.1:8000/v1/disk"

MB = 1024 * 1024
skip_fs = {'tmpfs', 'devtmpfs', 'squashfs'}
name = socket.gethostname()
time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

def send_cpu():
    for i, p in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
        try:
            r = requests.post(cpu_url, json={
                "hostname": name,
                "date": time,
                "cpu_core": f"cpu{i}",
                "cpu_used": f"{p:.1f}%",
                "cpu_free": f"{100 - p:.1f}%"
            })
            print(f"CPU cpu{i} 提交{'成功' if r.status_code == 200 else '失败'}")
        except Exception as e:
            print(f"CPU cpu{i} 错误：{type(e).__name__}")

def send_mem():
    try:
        m = psutil.virtual_memory()
        r = requests.post(mem_url, json={
            "hostname": name,
            "date": time,
            "used": m.used // MB,
            "free": m.free // MB,
            "total": m.total // MB,
            "used_percent": f"{m.percent:.1f}%"
        })
        print(f"内存 提交{'成功' if r.status_code == 200 else '失败'}")
    except Exception as e:
        print(f"内存 错误：{type(e).__name__}")

def send_disk():
    for d in psutil.disk_partitions():
        if d.fstype.lower() in skip_fs:
            continue
        try:
            u = psutil.disk_usage(d.mountpoint)
            r = requests.post(disk_url, json={
                "hostname": name,
                "date": time,
                "f_type": d.fstype,
                "used": round(u.used / MB, 1),
                "free": round(u.free / MB, 1),
                "total": round(u.total / MB, 1),
                "used_percent": f"{u.percent:.1f}%",
                "mountpoint": d.mountpoint.replace('\\', '/')
            })
            print(f"磁盘 {d.mountpoint} 提交{'成功' if r.status_code == 200 else '失败'}")
        except Exception as e:
            print(f"磁盘 {d.mountpoint} 错误：{type(e).__name__}")

if __name__ == '__main__':
    send_cpu()
    send_mem()
    send_disk()